//
//  VRFlowLayout.m
//  MyDemos
//
//  Created by Veer on 16/8/15.
//  Copyright © 2016年 veer. All rights reserved.
//

#import "VRFlowLayout.h"

@implementation VRFlowLayout

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    
    return YES;
}

- (void)prepareLayout
{
    [super prepareLayout];
    
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //设置内边距
    CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width)*0.5;
    self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
}


- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    
    NSArray *attrArray = [super layoutAttributesForElementsInRect:rect];
    
    CGFloat collectionCenterX = self.collectionView.width * 0.5 + self.collectionView.contentOffset.x;
    
    for (UICollectionViewLayoutAttributes *attr in attrArray) {
        
        CGFloat cellX = attr.center.x;
        CGFloat delta = ABS(cellX - collectionCenterX);
        
        CGFloat scale = 1 - delta / self.collectionView.width;
        attr.transform = CGAffineTransformMakeScale(scale, scale);
    }
    return attrArray;
}


- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    
    CGRect rect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.width, self.collectionView.height);
    NSArray *attrArray = [self layoutAttributesForElementsInRect:rect];
    
    CGFloat collectionCenterX = self.collectionView.width * 0.5 + proposedContentOffset.x;
    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attr in attrArray) {
        
        if (ABS(minDelta) > ABS(attr.center.x - collectionCenterX)) {
            minDelta = attr.center.x-collectionCenterX;
        }
    }
    
    proposedContentOffset.x += minDelta;
    return proposedContentOffset;
}




@end
